package lib

import (
	"ManageServer/defs/dbs"
	"github.com/gin-gonic/gin"
	"github.com/golang-module/carbon"
)

func CheckToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		//获取登录token
		token := c.GetHeader("Authorization")
		if token == "" {
			c.JSON(200, gin.H{
				"code": "401",
				"msg":  "用户未登录",
				"data": map[string]interface{}{},
			})
			c.Abort()
			return
		}
		//数据库验证
		var platformToken dbs.DbPlatformToken
		platformToken.Token = token
		if err := platformToken.Get(); err != nil {
			c.JSON(200, gin.H{
				"code": "401",
				"msg":  "用户未登录",
				"data": map[string]interface{}{},
			})
			c.Abort()
			return
		}
		//对比有效期  token 是否到期
		if !carbon.Parse(platformToken.EndAt.Format("2006-01-02 15:04:05")).Gt(carbon.Now()) {
			c.JSON(200, gin.H{
				"code": "401",
				"msg":  "用户未登录",
				"data": map[string]interface{}{},
			})
			c.Abort()
			return
		}
		reqIP := c.ClientIP()
		if reqIP != platformToken.Ip {
			c.JSON(200, gin.H{
				"code": "401",
				"msg":  "用户未登录",
				"data": map[string]interface{}{},
			})
			c.Abort()
			return
		}
		c.Next()
	}
}
